package com.cupk.carManageMaster.securityComponent;

import com.cupk.carManageMaster.common.domain.User;
import com.cupk.carManageMaster.common.mapper.UserMapper;
import com.cupk.carManageMaster.core.service.UserPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findUserByName(username);
        System.out.println("**************" + user.getUser_password() + "*************");

//        这是前端干的加密
        String password = bCryptPasswordEncoder.encode(user.getUser_password());
        user.setUser_password(password);

        //        验证用户名是否为空
        if (!StringUtils.hasLength(username)) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        //        验证用户名是否正确
        if (user == null) {
            throw new UsernameNotFoundException("用户名错误！！");
        }
        //获取用户权限，并把其添加到GrantedAuthority中
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        String menuPermission = userPermissionService.getMenuPermission(user);
        System.out.println(menuPermission);
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(menuPermission.toString());
        System.out.println(grantedAuthority);
        grantedAuthorities.add(grantedAuthority);
        System.out.println(grantedAuthorities);

        //方法的返回值要求返回UserDetails这个数据类型，  UserDetails是接口，找它的实现类就好了
        return new org.springframework.security.core.userdetails.User(username, user.getUser_password(), grantedAuthorities);
    }


}
